<?php

class User_UserController extends Zend_Controller_Action {

    public function init() {
        /* Init ialize action controller here */
    }

    public function addAction() {
        $id = $this->_getParam('id', 'none');
        if ($id == 'sdjlASKDWS') {
            $this->_helper->layout()->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $model = new Departament_Model_DbTable_Departament();
            echo $model->getCombo();
            return;
        }
        $form = new User_Form_User();
        $elem = $form->getElement('idgroup');
        $group = new Groups_Model_DbTable_Groups();
        $group = $group->getCombo();
        $elem->addMultiOptions($group);
        $elem1 = $form->getElement('client_departament');
        $c_d = new Departament_Model_DbTable_Departament();
        $data = $c_d->getCombo();
        if ($data != null)
            $elem1->addMultiOptions($data);
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                unset($formData['submit']);
                $formData['password'] = md5($formData['password']);
                $userForm = new User_Model_DbTable_User();
                $userForm->add($formData);
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Usuario adicionado con exito.');
                $this->_helper->redirector->gotoUrlAndExit('/user/user/view');
            } else {
                $form->populate($formData);
                $this->view->form = $form;
            }
        } else {
            $formData = $this->getRequest()->getPost();
            $form->populate($formData);
            $this->view->form = $form;
        }
    }

    public function editAction() {
        $id = $this->_getParam('id', 'none');
        if (!is_numeric($id) or $id <= 0) {
            $this->_helper->FlashMessenger()->setNamespace('error')->addMessage('Ha ocurrido un error en la URL.');
            $this->_helper->redirector->gotoUrlAndExit('/user/user/view');
        }
        $form = new User_Form_User();
        $elem = $form->getElement('idgroup');
        $group = new Groups_Model_DbTable_Groups();
        $group = $group->getCombo();
        $elem->addMultiOptions($group);
        $cli_dep = $form->getElement('client_departament');
        $user_type = new User_Model_DbTable_User();
        $user_type = $user_type->fetchRow("id = $id");
        if ($user_type['type'] == 'CLIENT') {
            $c_c = new Client_Model_DbTable_Client();
            $data = $c_c->getCombo();
        } else {
            $c_d = new Departament_Model_DbTable_Departament();
            $data = $c_d->getComboDep();
        }
        $cli_dep->addMultiOptions($data);
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            $userForm = new User_Model_DbTable_User();
            if (trim($formData['password']) != "") {
                $formData['password'] = md5($formData['password']);
            } else {
                $formData['password'] = $userForm->getPass($id);
            }
            if ($form->isValid($formData)) {
                unset($formData['submit']);
                $userForm->edit($formData, $this->_getParam('id'));
                $this->_redirect('/user/user/view');
            } else {
                $form->populate($formData);
                $this->view->form = $form;
            }
        } else {
            $formData = new User_Model_DbTable_User();
            $formData = $formData->fetchRow("id=" . (int) $id)->toArray();
            $form->populate($formData);
            $this->view->form = $form;
        }
    }

    public function deleteAction() {
        $id = $this->_getParam('id', 0);
        if ($id != 0 && $id != 1) { // Never delete superadmin
            $userForm = new User_Model_DbTable_User();
            $userForm->remove($id);
            $this->_helper->FlashMessenger()->setNamespace('succcess')->addMessage('Usuario eliminado con exito');
            $this->_helper->redirector->gotoUrlAndExit('/user/user/view');
        } else {
            $this->_helper->FlashMessenger()->setNamespace('error')->addMessage('No puede eliminar el usuario super admin');
            $this->_helper->redirector->gotoUrlAndExit('/user/user/view');
        }
    }

    public function viewAction() {
        $userForm = new User_Model_DbTable_User();
        $this->view->users = $userForm->view();
    }

    public function userclientAction() {
        $user = new User_Model_DbTable_User();
        $this->view->users = $user->fetchAll("type = 'CLIENT'");
    }

    /**
     * Cambiar perfil de usuario
     */
    public function changeProfileAction() {
        $request = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        $userDB = new User_Model_DbTable_User();
        if ($request->isPost()) {
            $data = $request->getParams();
            $dataUser = array(
                'nombre' => $data['nombre'],
                'apellidos' => $data['apellidos'],
                'email' => $data['email'],
                'telefono' => $data['telefono'],
                'username' => $data['username']
            );
            $flag = $userDB->update($dataUser, 'id=' . $auth->getIdentity()->id);
            if ($flag > 0) {
                $this->view->user = $data;
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Perfil actualizado.');
                $this->_helper->redirector->gotoUrlAndExit('/user/user/change-profile');
            }
        } else {
            $res = $userDB->fetchRow('id=' . $auth->getIdentity()->id);
            $this->view->user = $res;
        }
    }

    /**
     * Cambiar password de usuario
     */
    public function changePasswordAction() {
        $request = $this->getRequest();
        $auth = Zend_Auth::getInstance();
        $userDB = new User_Model_DbTable_User();
        if ($request->isPost()) {
            if (md5($request->getParam('password')) == $auth->getIdentity()->password) {
                $data = array('password' => md5($request->getParam('newpass')));
                $userDB->update($data, 'id=' . $auth->getIdentity()->id);

                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Nueva contraseña guardada.');
                $this->_helper->redirector->gotoUrlAndExit('/user/user/change-password');
            } else {
                $this->_helper->FlashMessenger()->setNamespace('error')->addMessage('Contraseña actual incorrecta.');
                $this->_helper->redirector->gotoUrlAndExit('/user/user/change-password');
            }
        } else {
            $this->view->user = $auth->getIdentity();
        }
    }

    /**
     * Acciones usuario admin-cliente (ex: Tigo)
     * solo usuarios internos de tigo.
     */
    public function usuarioAddAction() {
        $request = $this->getRequest();
        $userDB = new User_Model_DbTable_User();
        if ($request->isPost()) {
            $data = array(
                'nombre' => $request->getParam('nombre'),
                'apellidos' => $request->getParam('apellidos'),
                'email' => $request->getParam('email'),
                'username' => $request->getParam('username'),
                'password' => md5($request->getParam('password')),
                'telefono' => $request->getParam('telefono'),
                'client_departament' => 1,
                'type' => 'CLIENT-INTERNAL',
                'idgroup' => 15,
                'estado' => 1,
                'area' => $request->getParam('area'),
            );
            $index = $userDB->insert($data);
            if ($index > 0) {
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Usuario adicionado correctamente.');
                $this->_helper->redirector->gotoUrlAndExit('/user/user/usuario-list');
            }
        }
    }

    public function usuarioEditAction() {
        $request = $this->getRequest();
        $userDB = new User_Model_DbTable_User();
        $data = array();
        if ($request->isPost()) {
            $data['nombre'] = $request->getParam('nombre');
            $data['apellidos'] = $request->getParam('apellidos');
            $data['email'] = $request->getParam('email');
            $data['username'] = $request->getParam('username');
            $data['telefono'] = $request->getParam('telefono');
            $data['area'] = $request->getParam('area');
            if ($request->getParam('password') != '')
                $data['password'] = md5($request->getParam('password'));

            $index = $userDB->update($data, 'id=' . $request->getParam('id'));
            if ($index > 0) {
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Usuario editado correctamente.');
                $this->_helper->redirector->gotoUrlAndExit('/user/user/usuario-list');
            }
        } else {
            $user = $userDB->fetchRow("id=" . $request->getParam('id'));
            $this->view->user = $user;
        }
    }

    public function usuarioListAction() {
        $userDB = new User_Model_DbTable_User();
        $this->view->users = $userDB->fetchAll('client_departament = 1 and type="CLIENT-INTERNAL" and estado=1');
    }

    public function usuarioDeleteAction() {
        $request = $this->getRequest();
        $userDB = new User_Model_DbTable_User();
        $index = $userDB->update(array('estado'=>0), "id=" . $request->getParam('id'));
        if ($index > 0) {
            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Usuario eliminado.');
            $this->_helper->redirector->gotoUrlAndExit('/user/user/usuario-list');
        }
    }

}

